import ArticleItem from '@/components/ArticleItem';
import NavBar from '@/components/Navbar';
import { useAppSelector } from '@/store';
import { clearresultAction, getresultAction } from '@/store/action/search';
import { InfiniteScroll } from 'antd-mobile';
import { useEffect, useRef } from 'react';
import { useDispatch } from 'react-redux';
import { useLocation } from 'react-router-dom';
import styles from './index.module.scss';

export default function SearchResult() {
  const { search } = useLocation();
  const urlParms = new URLSearchParams(search);
  const keyword = urlParms.get('q') as string;

  const dispatch = useDispatch();
  // useEffect(() => {
  //   dispatch(getresultAction(keyword));
  // }, [keyword, dispatch]);

  useEffect(() => {
    dispatch(clearresultAction());
  }, [dispatch]);
  const pageRef = useRef(0);
  const { results } = useAppSelector((state) => state.search);
  const handleLoadMore = async () => {
    // 2. 让page累加1
    pageRef.current = pageRef.current + 1;
    // 2.2 让page累加1，并且传给Action
    await dispatch(getresultAction(keyword, pageRef.current));
  };
  const hasMore = pageRef.current * 10 <= results.length;
  return (
    <div className={styles.root}>
      {/* 顶部导航栏 */}
      <NavBar fixed>搜索结果</NavBar>

      <div className="article-list">
        {results.map((item) => (
          <ArticleItem key={item.art_id} data={item} />
        ))}
      </div>
      <InfiniteScroll loadMore={handleLoadMore} hasMore={hasMore} />
    </div>
  );
}
